package cn.tedu.egweibo1.controller;

import cn.tedu.egweibo1.mapper.UserMapper;
import cn.tedu.egweibo1.pojo.bto.UserLoginDTO;
import cn.tedu.egweibo1.pojo.bto.UserRegDto;
import cn.tedu.egweibo1.pojo.entity.User;
import cn.tedu.egweibo1.pojo.vo.UserVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import javax.servlet.annotation.HttpConstraint;
import javax.servlet.http.HttpSession;
import java.util.Date;

@Api(tags = "01.用户模块")
@Slf4j
@RestController
@RequestMapping("/v1/users/")
public class UserController {

    @Autowired
    private UserMapper userMapper;

    @ApiOperation(value = "注册功能")
    @PostMapping("reg")
    public int reg(@RequestBody UserRegDto userRegDto) {
        log.debug("userRegDto = {}", userRegDto);
        String username = userRegDto.getUsername();
        UserVO userVO = userMapper.selectUser(username);
        log.debug("userVO = {}", userVO);
        if (userVO != null) {
            return 2;
        }
        User user = new User();
        BeanUtils.copyProperties(userRegDto, user);
        user.setCreated(new Date());
        userMapper.insert(user);
        return 1;
    }

    @ApiOperation(value = "登录功能")
    @PostMapping("login")
    public int login(@RequestBody UserLoginDTO userLoginDTO, @ApiIgnore HttpSession session) {
        log.debug("userLoginDTO = {}", userLoginDTO);
        String username = userLoginDTO.getUsername();
        UserVO userVO = userMapper.selectUser(username);
        session.setAttribute("user", userVO);
        log.debug("userVO = " + userVO);
        if (userVO == null) {
            return 3;
        }
        if (userVO.getPassword().equals(userLoginDTO.getPassword())) {
            return 1;
        }
        return 2;
    }

    @ApiOperation(value = "获取当前用户功能")
    @GetMapping("currentUser")
    public UserVO currentUser(@ApiIgnore HttpSession session) {
        UserVO userVO = (UserVO) session.getAttribute("user");
        return userVO;
    }

    @ApiOperation(value = "退出登录功能")
    @GetMapping("logout")
    public void logout(@ApiIgnore HttpSession session) {
        session.removeAttribute("user");
    }

}
